/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package axil.stdlib.money.type;

import axil.api.AxilObject;
import axil.api.AxilType;
import axil.api.Formatting;
import axil.api.Persona;
import axil.framework.config.Configuration;
import axil.stdlib.numbers.type.Decimal;
import axil.stdlib.numbers.type.Num;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static axil.framework.Functions.*;


/**
 * The Axil object representing a monetary amount. Money contains both a currency
 * and an amount. Support is provided for flexible currency conversion, but you
 * need to support the converters.
 */
public class Money extends Num {
	public static final AxilType type = Money_Type.object;
	public static final Money zero = new Money(Decimal.zero, Currency.any());
	private static List<CurrencyConverter> converters =
	    new ArrayList<CurrencyConverter>();
	static {
		/**
		 * Install all of the currency converters specified in the configuration.
		 * Support for currency is completely optional,so there may not be any
		 * currency converters. Also, it is possible to work with a single
		 * currency, and thus not need currency converters, either.
		 */
		for (String classname :
		        Configuration.axil().list("currency-converters", false)) {
			converters.add(construct(CurrencyConverter.class, classname));
		}
	}

	private Decimal amount;
	private Currency currency;


	public Money(Decimal amount, Currency currency) {
		assert amount != null;
		assert currency != null;

		this.amount = amount;
		this.currency = currency;
	}


	/**
	 * Get the type metadata for this object. The type metadata contains
	 * information about the type itself, as an object.
	 */
	public AxilType type() {
		return type;
	}


	/**
	 * Tell the magnitude of this numeric value. This is used in all arithmetic
	 * computations to ensure like objects are used.
	 */
	public int kind() {
		return MONEY;
	}


	/**
	 * Return the canonical representation of a zero value in this numeric
	 * type.
	 */
	public Num zero() {
		return zero;
	}


	/**
	 * Get the underlying value for this numeric object. For most numbers, they
	 * simply return themselves, but for compound numbers (such as percent and
	 * money) the return the underlying value.
	 */
	public Num number() {
		return amount;
	}


	public Decimal amount()		{
		return amount;
	}
	public Currency currency()	{
		return currency;
	}


	/**
	 * Return the value of this object as an object of the indicated size. It
	 * can be safely assumed that the caller intended whatever side effects
	 * occur as part of the conversion are intentional.
	 */
	public Num as(int kind) {
		return amount.as(kind);
	}


	/**
	 * Returns a hash code value for the object. All Axil values must provide a
	 * meaningful implementation of this function to enable themselves to be
	 * placed in a map or set.
	 */
	protected int hash() {
		return amount().hashCode();
	}


	/**
	 * Tell if this number has any significant fractional digits. For example,
	 * the number 3.1 would return true, but 3.0 would not.
	 */
	public boolean fractional() {
		return amount.fractional();
	}


	/**
	 * Get this value as an integer value, discarding any fractional component.
	 * For example, 12.65 returns the integer value 12. No rounding is performed,
	 * only truncation. If the value is greater than what can fit in a 64-bit
	 * integer, then an exception is thrown.
	 */
	public long whole() {
		return amount.whole();
	}


	/**
	 * Get the fractional portion of this numeric value as a floating point
	 * value. For example, 12.325 returns a value of 0.325. If there is no
	 * fractional portion, then 0.0 is returned.
	 */
	public double tenths() {
		return amount.tenths();
	}


	/**
	 * Return a true value if this number is greater than zero. A value of zero
	 * returns a false value.
	 */
	public boolean positive() {
		return amount.positive();
	}


	/**
	 * Return a floating point representation of this object. It is understood
	 * the some loos of information may result. Invoking this method is
	 * accepting that side effect.
	 */
	public double fp() {
		return amount.fp();
	}


	/**
	 * Tell if this object is equivalent to the given object. The object given
	 * is never null. The object given may be of any type of value object.  If
	 * the given object is not a suitable type for comparison, a
	 * ClassCastException may be thrown.
	 */
	public boolean equalTo(AxilObject object) {
		if (object instanceof Money) {
			Money v = (Money)object;
			return amount.equals(v.amount) && currency == v.currency;
		}
		return amount.equalTo(object);
	}


	/**
	 * Compares this object with the specified object for order. If the given
	 * object is not a suitable type for comparison, a ClassCastException may
	 * be thrown.
	 *
	 * @param object
	 * 	The object to compare against. The given object cannot be null but may
	 * 	be any Axil object.
	 *
	 * @return
	 * 	Returns a negative integer, zero, or a positive integer as this object
	 * 	is less than, equal to, or greater than the specified object.
	 */
	public int comparedTo(AxilObject object) {
		Money v = (Money)object;
		if (v.currency != currency) {
			throw error(axil(), "different-currencies", nv("this", currency),
			            nv("other", v.currency));
		}
		return amount.compareTo(v.amount);
	}


	/**
	 * Add the given number of this number. This method can safely assume that
	 * the given value is not null and is of the exact same type as this value.
	 */
	public AxilObject add(AxilObject object) {
		Num n = (Num)object;
		if (n instanceof Money) {
			if (zilch(n)) {
				return this;
			}
			return new Money((Decimal)amount.add(check(n).amount), currency);
		}
		return new Money((Decimal)amount().add(n.as(DECIMAL)), currency);
	}


	/**
	 * Subtract the given number from this number. This method can safely assume
	 * that the given value is not null and is of the exact same type as this
	 * value.
	 */
	public AxilObject subtract(AxilObject object) {
		Num n = (Num)object;
		if (n instanceof Money) {
			if (zilch(n)) {
				return this;
			}
			return new Money((Decimal)amount.subtract(check(n).amount), currency);
		}
		return new Money((Decimal)amount().subtract(n.as(DECIMAL)), currency);
	}


	/**
	 * Multiply the given number by this number. This method can safely assume
	 * that the given value is not null and is of the exact same type as this
	 * value.
	 */
	public Num multiply(Num n) {
		if (n instanceof Money) {
			if (zilch(n)) {
				return new Money(Decimal.zero, this.currency);
			}
			return new Money((Decimal)amount.multiply(check(n).amount), currency);
		}
		return new Money((Decimal)amount().multiply(n.as(DECIMAL)), currency);
	}


	/**
	 * Divide this number by the given number. This method can safely assume
	 * that the given value is not null and is of the exact same type as this
	 * value.
	 */
	public Num divide(Num n) {
		if (n instanceof Money) {
			if (zilch(n)) {
				return new Money(Decimal.zero, this.currency);
			}
			return new Money((Decimal)amount.divide(check(n).amount), currency);
		}
		return new Money((Decimal)amount().divide(n.as(DECIMAL)), currency);
	}


	/**
	 * Round this value according to the rules of the given rounding mode and
	 * to the given number of significant fractional digits. A value of zero
	 * rounds this to a whole number.
	 */
	public Num round(RoundingMode mode, int digits) {
		return new Money((Decimal)amount.round(mode, digits), currency);
	}


	private Money check(Num other) {
		Money m = (Money)other;
		if (this.currency != m.currency) {
			throw error(axil(), "different-currencies",
			            nv("this", this.currency),
			            nv("other", m.currency));
		}
		return m;
	}


	public Money convert(Currency to, Date then, Date now) {
		for (CurrencyConverter c : converters) {
			Money m = c.convert(this, to, then, now);
			if (m != null) {
				return m;
			}
		}
		return null;
	}


	public Money convert(Currency to, Date then, Date now,
	                     CurrencyConverter using) {
		return using.convert(this, to, then, now);
	}


	public static CurrencyConverter converter(String ident) {
		for (CurrencyConverter c : converters) {
			if (c.identity().equals(ident)) {
				return c;
			}
		}
		return null;
	}


	/**
	 * Format this object in a locale-friendly manner. The string returned is
	 * a localized representation of this object using the locale and timezone
	 * associated with this persona. The formatting given is never null and
	 * matches formatting suitable for this type.
	 */
	public String format(Persona persona, Formatting formatting) {
		// TODO: Need better formatting supporting
		return currency.currency().getSymbol(loc(persona).locale()) +
		       amount.toString();
	}
}
